<?php
namespace App\Utils;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class Tianyancha{

    private $token = "";
    public function __construct(){}

    public function setToken($token){
        $this->token = $token;
    }

    public function getMessageByUrlToken($name){
        $result = array();
        $url = "http://open.api.tianyancha.com//services/open/ic/baseinfoV2/2.0";
        $params['name'] = $name;
        $res =  $this->httpGet($url, $params);
        $data = json_decode($res, true);
        if (!empty($data) && $data['error_code'] === 0){
            $result = $data['result'];
        }else{
            Log::info("getMessageByUrlToken failed:". $res);
        }
        return $result;
    }

    public function httpGet($url, &$params){
        $header['Authorization'] = $this->token;
        return Http::withHeaders($header)->get($url, $params);
    }

    public function request($url, $params = array()){
        try {

            if (!empty($params)){
                $url .= "?".http_build_query($params);
            }
            $header[] = 'Authorization:'.$this->token;
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $res = curl_exec($ch);
            curl_close($ch);
            return $res;
        }catch (\Exception $e){
            exit("Code:".$e->getCode()."\nException:".$e->getMessage()."\n");
        }
    }
}
